<template>
	<div id="user_container">
		<el-breadcrumb separator="/">
		  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
		  <el-breadcrumb-item :to="{ path: '/users' }"><a>用户列表</a></el-breadcrumb-item>
		</el-breadcrumb>

        <el-card class="box-card">
		  <el-row :gutter="20">
			  <el-col :span="9">
                  <el-input placeholder="请输入内容" class="input-with-select">
				    <el-button slot="append" icon="el-icon-search"></el-button>
				  </el-input>
			  </el-col>
			  <el-col :span="4">
			  	<el-button type="primary" @click="addUserdialogVisible = !addUserdialogVisible">添加用户</el-button>
			  </el-col>
		  </el-row>
	   <!--用户列表-->
		  <el-table :data="userList" border stripe>
	        <el-table-column type="index"></el-table-column>
	        <el-table-column label="姓名" prop="username"></el-table-column>
	        <el-table-column label="邮箱" prop="email"></el-table-column>
	        <el-table-column label="电话" prop="mobile"></el-table-column>
	        <el-table-column label="角色" prop="role_name"></el-table-column>
	        <el-table-column label="状态">
	          <template slot-scope="scope">
	          	<el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="userStateChange(scope.row)">
	            </el-switch>
	          </template>
	        </el-table-column>
	        <el-table-column label="操作" width="300px">
	          <template slot-scope="scope">
	        	<el-button type="primary" icon="el-icon-edit" size="mini" @click="getUserInfo(scope.row)"></el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
                <el-button type="warning" icon="el-icon-setting" size="mini" @click="allotRole(scope.row)"></el-button>	
	          </template>
	        </el-table-column>
	      </el-table>

	      <!--分页功能-->
	      <el-pagination
		    @size-change="userPageSizeChange"
		    @current-change="userPageCurrentChange"
		    :current-page="queryInfo.pagenum"
		    :page-sizes="[1, 2, 5, 10]"
		    :page-size="queryInfo.pagesize"
		    layout="total, sizes, prev, pager, next, jumper"
		    :total="total">
		  </el-pagination>
		</el-card>
		<!--添加用户对话框-->
		<el-dialog
		  title="添加用户"
		  :visible.sync="addUserdialogVisible"
		  width="50%"  @close="resetForm">
		  <el-form :model="addUserForm" status-icon :rules="addUserRules" ref="addUserForm" label-width="70px" class="demo-ruleForm">
			  <el-form-item label="用户名" prop="username">
			    <el-input v-model="addUserForm.username" autocomplete="off"></el-input>
			  </el-form-item>
			  <el-form-item label="密码" prop="password">
			    <el-input type="password" v-model="addUserForm.password" autocomplete="off"></el-input>
			  </el-form-item>
			  <el-form-item label="用户邮箱" prop="email">
			    <el-input v-model="addUserForm.email" autocomplete="off"></el-input>
			  </el-form-item>
			  <el-form-item label="用户手机" prop="mobile">
			    <el-input v-model="addUserForm.mobile" autocomplete="off"></el-input>
			  </el-form-item>
		  </el-form>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="addUserdialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="addUser">确 定</el-button>
		  </span>
		</el-dialog>
		<!--编辑用户对话框-->
		<el-dialog
		  title="编辑用户"
		  :visible.sync="editUserdialogVisible"
		  width="50%">
		  <el-form :model="editUserForm" status-icon :rules="editUserRules" ref="editUserForm" label-width="70px" class="demo-ruleForm">
			  <el-form-item label="Id" prop="id">
			    <el-input v-model="editUserForm.id" autocomplete="off" disabled></el-input>
			  </el-form-item>
			  <el-form-item label="用户邮箱" prop="email">
			    <el-input v-model="editUserForm.email" autocomplete="off"></el-input>
			  </el-form-item>
			  <el-form-item label="用户手机" prop="mobile">
			    <el-input v-model="editUserForm.mobile" autocomplete="off"></el-input>
			  </el-form-item>
		  </el-form>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="editUserdialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="updateUser">确 定</el-button>
		  </span>
		</el-dialog>
		<!--分配用户角色对话框-->
		<el-dialog
		  title="编辑用户"
		  :visible.sync="allotRoledialogVisible"
		  width="50%" @close="setRoleDialogClosed">
		   <div>
	          <p>当前的用户：{{userInfo.username}}</p>
	          <p>当前的角色：{{userInfo.role_name}}</p>
	          <p>分配新角色：
	          	<!-- v-model的值为当前被选中的el-option的 value 属性值 -->
	            <el-select v-model="selectedRoleId" placeholder="请选择">
	              <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
	              </el-option>
	            </el-select>
	          </p>
	        </div>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="allotRoledialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="updateUserRole">确 定</el-button>
		  </span>
		</el-dialog>
	</div>
</template>
<script>
export default {
	data () {
		//自定义验证
       var checkEmail = (rule,value,callback) => {
         const emailReg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
         if (value === '') {
         	callback(new Error("请输入邮箱"))
         }else if (!emailReg.test(value)) {
         	callback(new Error("请输入正确邮箱地址"))
         }
         callback()
       }
       var checkPhone = (rule,value,callback) => {
       	const phoneReg = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
       	if (value === '') {
       		callback(new Error("请输入手机号"))
       	}else if (!phoneReg.test(value)) {
       		callback(new Error("请输入正确的手机号码"))
       	}
       	callback()
       }
		return {
          queryInfo: {
          	query: '',
          	pagenum: 1,
          	pagesize: 2
          },
          userList: [],
          total: 0,
          // 用户状态
          userState: false,
          // 控制添加用户对话框开关
          addUserdialogVisible: false,
          // 控制编辑用户对话框开关
          editUserdialogVisible: false,
          // 控制分配角色对话框开关
          allotRoledialogVisible: false,
          // 添加用户对象
          addUserForm: {
          	username: 'admi1',
          	password: '123456',
          	email: '5@qq.com',
          	mobile: '13113920014'
          },
          // 编辑用户对象
          editUserForm: {
            id:0,
            email: '',
            mobile: ''
          },
          // 需要被分配角色的用户信息
          userInfo: {},
          // v-model的值为当前被选中的el-option的 value 属性值
          selectedRoleId:'',
          // rolesList 获取所有角色列表
          rolesList: [],
          // 添加用户的规则验证对象
          addUserRules: {
          	username: [
              { required: true, message: "用户名不能为空", trigger: "blur" },
			  { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          	],
          	password: [
			  { required: true, message: "请输入登录密码", trigger: "blur" },
			  { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
			],
			email: [
              { validator: checkEmail, trigger: 'blur' }
			],
			mobile: [
              { validator: checkPhone, trigger: 'blur'}
			]
          },
          // 编辑用户的规则验证对象
          editUserRules: {
          	email: [
              { validator: checkEmail, trigger: 'blur' }
			],
			mobile: [
              { validator: checkPhone, trigger: 'blur'}
			]
          }
		}
	},
	created () {
        this.getUserList()
	},
	methods: {
		async getUserList () {
			const { data: res } = await this.$http.get('users', { params: this.queryInfo })
			if(res.meta.status !== 200) {
				return this.$message.error('获取用户列表失败！')
			}
			console.log(res)
			this.userList = res.data.users
			this.total = res.data.total
		},
		// 监听每页显示条数的改变
		userPageSizeChange (pagesize) {
			this.queryInfo.pagesize = pagesize
			this.getUserList()
		},
		// 监听当前页码的改变
		userPageCurrentChange (currentPage) {
			this.queryInfo.pagenum = currentPage
			this.getUserList()
		},
		// 监听用户状态的改变并保存
		async userStateChange (userInfo) {
			// 保存用户状态需要通过api接口修改远程数据库用户状态
          const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
          if (res.meta.status !== 200) {
          	// 复原用户状态
          	userInfo.mg_state = !userInfo.mg_state
          	this.$message.error('更新用户状态失败')
          }
		  	this.$message.success('更新用户状态成功')
		},
          // 关闭对话框时重置添加用户表单
        resetForm () {
          	this.$refs.addUserForm.resetFields()
        },
        // 添加用户
        async addUser(){
        	// 在提交添加用户的网络请求前需要预校验
        	this.$refs.addUserForm.validate(valid => {
        		//如果验证不通过则终止后面程序运行
        		if(!valid) return
        	})
           // 验证通过则发出添加用户的网络请求 
          const { data: res} = await this.$http.post('users',this.addUserForm)
          // 判断是否添加用户成功
          if(res.meta.status !== 201) {
          	this.$message.error('添加用户失败')
          }
          this.$message.success('添加用户成功')

          // 关闭对话框
          this.addUserdialogVisible = false
          // 重新渲染用户列表
          this.getUserList()
        },
        // 使用户信息自动填充到表单上
        getUserInfo(userInfo){
        	this.editUserdialogVisible = !this.editUserdialogVisible
        	this.editUserForm.id = userInfo.id
        	this.editUserForm.email = userInfo.email
        	this.editUserForm.mobile = userInfo.mobile
        },
        // 更新用户信息
        async updateUser(){
        	this.$refs.editUserForm.validate(valid => {
        		if(!valid) return
        	})
            const { data: res } = await this.$http.put('users/'+this.editUserForm.id,{ email: this.editUserForm.email, mobile: this.editUserForm.mobile})
            if (res.meta.status !== 200 ){
            	this.$message.error('更新用户失败')
            }
            this.$message.success('更新用户信息成功')
            // 关闭对话框
            this.editUserdialogVisible = false
            // 重新渲染用户列表
            this.getUserList()
        },
        //删除用户
        async deleteUser (id) {
        	// 询问是否要删除用户 避免误删
        	const confirmResult = await this.$msgbox.confirm('是否确定删除用户这一操作，确定后将永久删除用户','提示',{ 
        		confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(val=>val)

            if (confirmResult !== 'confirm') {
		      return this.$message.info('已取消删除')
		    }
        	const { data: res } = await this.$http.delete('users/'+id)
        	console.log(res)
        	if(res.meta.status !== 200) {
        		this.$message.error('删除用户失败')
        	}else if(res.meta.status == 400){
        		this.$message.error('不允许删除admin用户')
        	}
        	
        	// 尾页最后一条数据删除后显示没有数据 必须要手动刷新页面才能更新页面到有数据的页面上
            // 检测 如果总页数 小于 当前页码 那么使当前页码等于总页数 强制更新用户信息

            let totalPage = Math.ceil((this.total-1)/this.queryInfo.pagesize)
            this.queryInfo.pagenum = totalPage<this.queryInfo.pagenum ? totalPage : this.queryInfo.pagenum
            this.queryInfo.pagenum = this.queryInfo.pagenum<1?1:this.queryInfo.pagenum
            this.$message.success('成功删除用户')
            this.getUserList()
        },
        //  为用户分配权限
        async allotRole (userInfo) {
          this.userInfo = userInfo
          const { data: res } = await this.$http.get('roles')
	      if (res.meta.status !== 200) {
	        return this.$message.error('获取角色列表失败！')
	      }

	      this.rolesList = res.data

	      this.allotRoledialogVisible = true
        },
        // 确认更新用户角色
        async updateUserRole () {
          if (!this.selectedRoleId) {
          	return this.$message.error('请选择要分配的角色！')
          }
          const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`,{ rid: this.selectedRoleId})
          if (res.meta.status !== 200) {
	        return this.$message.error('更新角色失败！')
	      }

	      this.$message.success('更新角色成功！')
	      this.getUserList()
	      this.allotRoledialogVisible = false
        },
        // 监听分配角色对话框的关闭事件
        setRoleDialogClosed () {
          this.selectedRoleId = ''
          this.userInfo = {}
        }
	}
}
</script>
<style>
</style>
